package com.jingdianjichi.wx.controller;

import com.jingdianjichi.wx.handler.WxChatMsgFactory;
import com.jingdianjichi.wx.handler.WxChatMsgHandler;
import com.jingdianjichi.wx.utils.MessageUtil;
import com.jingdianjichi.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
@RequestMapping("wx")
public class CallBackController {

    //微信token
    private static final String token = "da4gdf5";

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;

    /**
     * 验证微信签名,连通微信
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping("/callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("请求参数：signature:{}；timestamp:{}；nonce:{}；echostr:{}；",
                signature, timestamp, nonce, echostr);

        String sha1Str = SHA1.generateSHA1Signature(token, timestamp, nonce);
        log.info("sha1Str:{}", sha1Str);
        if (signature.equals(sha1Str)) {
            return echostr;
        }

        return "unknown";
    }


//    <xml>
//     <ToUserName><![CDATA[gh_a0946b2a49d2]]></ToUserName> 微信公众号的唯一标识
//            <FromUserName><![CDATA[ofonl65Hx6mnZhGT2bONEPooBIcY]]></FromUserName> openid,用户的唯一标识
//            <CreateTime>1734594323</CreateTime>  创建时间
//            <MsgType><![CDATA[event]]></MsgType> 动作类型：event表示关注
//            <Event><![CDATA[subscribe]]></Event>
//     <EventKey><![CDATA[]]></EventKey>
//     </xml>

    /**
     * 微信回调，提供用户关注后的信息
     *
     * @param requestBody   xml格式，用户关注后获取用户基本信息
     * @param signature
     * @param timestamp
     * @param nonce
     * @param msg_signature 加密的签名密文，非必须，可以用于明文测试用
     * @return
     */
    @PostMapping(value = "/callback", produces = "application/xml;charset=UTF-8")
    public String callback(@RequestBody String requestBody,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam(value = "msg_signature", required = false) String msg_signature) {
        log.info("\n微信回调请求参数：requestBody:{}；\nsignature:{}；timestamp:{}；nonce:{}；echostr:{}；",
                requestBody, signature, timestamp, nonce, msg_signature);
        //工具类解析 xml格式文本
        Map<String, String> msgMap = MessageUtil.parseXml(requestBody);
        //获取消息类型：
        String msgType = msgMap.get("MsgType");
        StringBuilder msgTypeKeySB = new StringBuilder();
        msgTypeKeySB.append(msgType);
        String event = msgMap.get("Event");
        if (!StringUtils.isEmpty(event)){
            msgTypeKeySB.append(".");
            msgTypeKeySB.append(event);
        }
        WxChatMsgHandler msgHandler = wxChatMsgFactory
                .getHandlerByMsgType(msgTypeKeySB.toString());

        if (Objects.isNull(msgHandler)){
            return "unknown";
        }
        //调用对应类型的消息处理 方法
        String replyContent = msgHandler.dealMsg(msgMap);
        log.info("replyContent:{}\n", replyContent);

        return replyContent;
    }
}
